"""
Copyright (c) 2023 - present SKbioinfo
"""

from flask_restful import Resource, reqparse
from flask import request,jsonify
from flask_login import login_required,current_user
from apps.NGS_API.record.interface_operate_his import parse_reason
from apps.NGS_API.stock.db_stock import *
from apps.NGS_API.connector.db_common import *
from apps.NGS_API.utils.log_helper import lg
from apps.NGS_API.common.db_table_config import *
from apps.NGS_API.record.history_util import *
pm = operation_monitor(table_name=ngs_op_log["name"])

'''
    Stock infos.NGS_API
'''
class interfaceStock(Resource):
    @login_required
    def get(self):
        try:
            ### Setting ###
            mapping = {
                None:"NA",
                1:"入库",
                -1:"出库",
                0:"未入库"
            }
            ### Stocks ###
            stocks = {}
            ### receive stock infos from database ###
            stock_base_info = query_stock_info(
                stock = sample_stock_db["name"],
                sample = sample_db["name"]
            )
            stock_infos = []
            for stock in stock_base_info:
                stock_infos.append({
                    "id": stock[0],
                    "proj_id": stock[1],
                    "stc_id": stock[2],
                    "sam_id": stock[3],
                    "status": mapping[stock[4]],
                    "stc_lab": stock[5],
                    "stc_loc": stock[6],
                    "istc_type": stock[7],
                    "istc_user": stock[8],
                    "istc_ch_user": stock[9],
                    "istc_amount": stock[10],
                    "istc_time": stock[11],
                    "cur_amount": stock[12],
                    "ostc_type": stock[13],
                    "ostc_user": stock[14],
                    "ostc_ch_user": stock[15],
                    "ostc_amount": stock[16],
                    "ostc_time": stock[17],
                    "cre_time": stock[18],
                    "md_time": stock[19],
                    "flag": False
                })
            stocks["stock_infos"] = stock_infos
            response=jsonify(stocks)
            response.status_code = 202
            return response
        except Exception as e:
            lg.error(e)

class interfaceStockID(Resource):
    def delete(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                ### SQL: record reason details ###
                reason_details = parse_reason(data=request.json)
                ## SQL: record user operation ###
                record_user_operate(
                    pm = pm,
                    current_user = current_user,
                    record_table = ngs_op_log["name"],
                    resource_table = sample_stock_db["name"],
                    ch_user = current_user,
                    type_name = "delete",
                    cols = '''
                        sample_id
                    ''',
                    id = id,
                    reason_details = reason_details
                )
                ### SQL: ###
                update_sql = '''
                    UPDATE {table_name} SET 
                        instock_amount=0,
                        cur_amount=0,
                        status=0
                    WHERE id = \"{id}\" 
                '''.format(
                    table_name=sample_stock_db["name"],
                    id=id
                )
                update_info(update_sql)
                return id
        except Exception as e:
            lg.error(e)
    @login_required     
    def post(self,id):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument("reason",type=str,help="",required=True)
            parser.add_argument("extra",type=str,help="",required=True)
            args=parser.parse_args()
            ### SQL: record reason details ###
            reason_details = parse_reason(data=args)
            ### SQL: record user operation ###
            record_user_operate(
                pm = pm,
                current_user = current_user,
                record_table = ngs_op_log["name"],
                resource_table = sample_stock_db["name"],
                ch_user = current_user,
                type_name = "delete",
                cols = '''
                    sample_id
                ''',
                id = id,
                reason_details = reason_details
            )
            ### SQL: update stock table ###
            update_sql = '''
                UPDATE {table_name} SET 
                    instock_amount=0,
                    cur_amount=0,
                    status=0
                WHERE id = \"{id}\" 
            '''.format(
                table_name=sample_stock_db["name"],
                id=id
            )
            update_info(update_sql)
        except Exception as e:
            lg.error(e)
            
    def put(self,id):
        try:
            if request.data.decode(encoding='UTF-8',errors='strict') == "-1":
                pass
            else:
                parser = reqparse.RequestParser()
                parser.add_argument('id',type=str,required=True,help="ID输入有误")
                parser.add_argument('proj_id',type=str,required=True,help="项目ID输入错误!")
                parser.add_argument('sam_id',type=str,required=True,trim=True,help='样品ID验证错误!') 
                parser.add_argument('stc_id',type=str, required=True,help='存货ID验证错误!')
                parser.add_argument('stc_loc', type=str, required=True,help="存货位置验证错误!")
                parser.add_argument('istc_type',type=str,required=True,help="存货类型验证错误!")
                parser.add_argument('istc_time',type=str,required=True,help="操作时间有误!")
                parser.add_argument('istc_amount',type=int,required=True,help="存货量输入有误")
                parser.add_argument('cur_amount',type=int,required=True,help="存货现有量输入有误")
                parser.add_argument('istc_user', type=str,required=True,help="入库人有误!")
                parser.add_argument('istc_ch_user', type=str,required=True,help="审核人ID有误!")
                args=parser.parse_args(strict=True)
                stock_update_sql="""
                UPDATE {table_name} SET 
                    stock_id=\"{stock_id}\",
                    sample_id=\"{sample_id}\",
                    stock_locale=\"{stock_locale}\",
                    instock_type=\"{instock_type}\",
                    instock_amount={instock_amount},
                    cur_amount={cur_amount},
                    instock_user=\"{instock_user}\",
                    instock_check_user=\"{instock_check_user}\"            
                WHERE id=\"{id}\"
                """.format(
                    table_name=sample_stock_db["name"],
                    stock_id=args.get("stc_id"),
                    sample_id=args.get("sam_id"),
                    stock_locale=args.get("stc_loc"),
                    instock_type=args.get("istc_type"),
                    instock_amount=args.get("istc_amount"),
                    cur_amount=args.get("cur_amount"),
                    instock_user=args.get("istc_user"),
                    instock_check_user=args.get("istc_ch_user"),
                    id=args.get("id")
                )
                update_info(update_sql=stock_update_sql)
            return id
        except Exception as e:
            lg.error(e)
